package Chapter7point4;

//1、Account账户类，记录账户名和金额，提供put()存款方法和get()取款方法
public class Account {
    String name;
    double balance;

    public Account(String name) {
        this.name = name;
        this.balance = 0;
    }

    public void put(double value) {  //存款操作，参数为存入金额。提供给存款线程调用
        if (value > 0)
            this.balance += value;
    }

    //取款操作，参数为取款金额，返回实际取到的金额，提供给取款线程调用
    public double get(double value) {
        if (value <= 0)
            return 0;
        if (value <= this.balance)
            this.balance -= value;
        else {
            value = this.balance;
            this.balance = 0;
        }
        return value;
    }
}

//2、SaveThread存款线程类，提供对指定账户的存款操作
class SaveThread extends Thread {
    private Account account;
    private double value;

    public SaveThread(Account account, double value) {
        this.account = account;
        this.value = value;
    }

    public void run() {
        double howmatch = this.account.balance;  //查看账户余额
        //此处执行其他操作，线程执行可能被打断；也可调用sleep(1)语句模拟线程被打断
        this.account.put(this.value);
        System.out.println(this.getClass().getName() + "," + this.account.name + "账户,现有" +
                howmatch + ",存入" + this.value + ",余额" + this.account.balance);
    }
}

//3、FetchThread取款线程类，提供对指定账户的取款操作
class FetchThread extends Thread {
    private Account account;
    private double value;

    public FetchThread(Account account, double value) {
        this.account = account;
        this.value = value;
    }

    public void run() {
        double howmatch = this.account.balance;
        //此处执行其他操作，线程执行可能被打断；也可调用sleep(1)语句模拟线程被打断
        System.out.println(this.getClass().getName() + "," + this.account.name + "账户,现有" +
                howmatch + ",取走" + this.account.get(this.value) + ",余额" + this.account.balance);
    }

    public static void main(String[] args) {
        Account wang = new Account("Wang");
        (new SaveThread(wang, 100)).start();
        (new SaveThread(wang, 200)).start();
        (new SaveThread(wang, 300)).start();
        (new SaveThread(new Account("Li"), 100)).start();
        ;
    }
}
